﻿using ApplicationModels.A02.Identities;
using ApplicationModels.A06.Socializes;
using AutoMapper;
using Commons.Responses;
using EntityModels.E06.Socializes;
using IApplicationServices;
using IRepositories;

namespace ApplicationService
{
    public class FollowService : BaseApplicationService<int, Follow, FollowAM>, IFollowService
    {
        public FollowService(IBaseRepository<int, Follow> repository, IMapper mapper) : base(repository, mapper)
        {
            
        }

        public async Task<DatasResponse<FollowAM>> GetFansListAsync(string userId)
        {
            var res = await Repository.GetAllAsync(f => f.FollowerId == Guid.Parse(userId));
            var fans = Mapper.Map<List<FollowAM>>(res.Datas);
            var total = res.Total;
            return new DatasResponse<FollowAM>(total,fans);
        }

        public async Task<DatasResponse<FollowAM>> GetFollowingListAsync(string userId)
        {
            var res = await Repository.GetAllAsync(f => f.AppUserId == Guid.Parse(userId));
            var followings = Mapper.Map<List<FollowAM>>(res.Datas);
            var total = res.Total;
            return new DatasResponse<FollowAM>(total, followings);
        }

        public async Task<bool> IsFollowingAsync(string appUserId, string followerId)
        {
            return await Repository.AnyAsync(f => f.AppUserId == Guid.Parse(appUserId) && f.FollowerId == Guid.Parse(followerId));
        }

        public async Task<bool> IsMutuallyFollowingAsync(string appUserId, string followerId)
        {
            var user1FollowsUser2 = await IsFollowingAsync(appUserId, followerId);
            var user2FollowsUser1 = await IsFollowingAsync(followerId, appUserId);
            return user1FollowsUser2 && user2FollowsUser1;
        }

        public async Task<MessageResponse> UnFollow(string appUserId, string followerId)
        {
            var follow = await Repository.GetAsync(x => x.AppUserId == Guid.Parse(appUserId) && x.FollowerId == Guid.Parse(followerId));
            return await Repository.DeleteAsync(follow.Id);
        }
    }
}
